<template>
    <el-container>

    <el-main>
        <el-form :inline="true"  class="demo-form-inline" v-model="admin">
       
        <el-row :gutter="20">
            <el-col :span="7">
                <el-form-item label="用户名称">
                    <el-input  placeholder="用户名称" v-model="formData.name"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="7">
                <el-form-item label="手机号码">
                    <el-input  placeholder="手机号码" v-model="formData.phone"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="5"></el-col>
            <el-col :span="5"></el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="7">
                <el-form-item label="用户状态">
                    <el-select placeholder="用户状态" v-model="formData.status">
                        <el-option label="启用" value="1"></el-option>
                        <el-option label="禁用（离职）" value="2"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="7">
                <el-form-item label="活动时间">
                    <el-date-picker
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        style="width: 250px;"
                        v-model="formData.dateTime"
                        >
                    </el-date-picker>
                </el-form-item>
            </el-col>
            <el-col :span="5">
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
                </el-form-item>
                <el-form-item>
                <el-button icon="el-icon-refresh-right" @click="reset">重置</el-button>
                </el-form-item>
            </el-col>
            <el-col :span="5">
            </el-col>
        </el-row>

        <el-row>
            <el-button type="primary" plain icon="el-icon-plus" @click="centerDialogVisible = true">新增</el-button>
            <el-button type="danger" plain icon="el-icon-delete" @click="deleteIds">删除</el-button>
            <el-button type="warning" plain icon="el-icon-download" @click="exportproperty()">导出</el-button>
        </el-row>
    </el-form>

    <!-- table -->
        <el-table
        :data="admin"
        :row-key="row=>row.id"
        @selection-change="handleSelectionChange"
        style="width: 100%">
        <el-table-column
        type="selection"
        width="55">
        </el-table-column>
        <el-table-column type="expand">
        <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="具体信息">
                <span>{{ props.row.name }}</span>
            </el-form-item>
            <el-form-item label="编号">
                <span>{{ props.row.id }}</span>
            </el-form-item>
            <el-form-item label="账号">
                <span>{{ props.row.account }}</span>
            </el-form-item>
            <el-form-item label="身份证信息">
                <span>{{ props.row.identificationCard }}</span>
            </el-form-item>
            <el-form-item label="创建时间">
                <span>{{ props.row.createTime }}</span>
            </el-form-item>
            <el-form-item label="更新时间">
                <span>{{ props.row.updateTime }}</span>
            </el-form-item>
            <el-form-item label="手机号码">
                <span>{{ props.row.mobile }}</span>
            </el-form-item>
            <el-form-item label="部门">
                <span>{{ props.row.apartment }}</span>
            </el-form-item>
            <el-form-item label="权限">
                <span>{{ props.row.authority }}</span>
            </el-form-item>
            <el-form-item label="状态">
                <span>{{ props.row.status == true?"启用中":"禁用中" }}</span>
            </el-form-item>
            </el-form>
        </template>
        </el-table-column>
        <el-table-column
        label="管理员编号"
        prop="id">
        </el-table-column>
        <el-table-column
        label="管理员实名"
        prop="name">
        </el-table-column>
        <el-table-column
        label="部门"
        prop="apartment">
        </el-table-column>

        <el-table-column
        label="手机号码"
        prop="mobile">
        </el-table-column>

        <el-table-column
        label="状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            @change="handleSwitchChange(scope.row)"
            active-color="#13ce66"
            inactive-color="#ff4949"
         > 
         <!-- v-model="scope.row.status" -->
          </el-switch>
        </template>
        </el-table-column>

        <el-table-column
        label="创建时间"
        prop="createTime">
        </el-table-column>

        <el-table-column label="操作">
      <template slot-scope="scope">
        <!-- <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">编辑</el-button> -->
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </el-main>
    
    <!-- 增加页面 -->
    <el-dialog
      title="信息录入"
      :visible.sync="centerDialogVisible"
      width="30%"
      center>

      <el-input placeholder="请输入内容" v-model="createPhone">
        <template slot="prepend">请输入手机号</template>
      </el-input>
      <span style="display: block; height: 20px;"></span>
      <el-input placeholder="请输入内容" v-model="createName">
        <template slot="prepend">请输入实名</template>
      </el-input>
      <el-select v-model="selectedRoleId" placeholder="请选择角色" @change="handleRoleSelection" style="margin-top:20px;width: 100%;">
        <el-option
          v-for="role in roleValue"
          :key="role.roleId"
          :label="role.roleName"
          :value="role.roleId">
        </el-option>
      </el-select>

      <el-dialog
            width="30%"
            title="验证"
            :visible.sync="innerVisible"
            append-to-body>
            <el-input placeholder="请输入登录密码验证"  type="password" v-model="validPassword" show-password>
              <template slot="prepend">请输入密码</template>
            </el-input>
            <span slot="footer" class="dialog-footer">
              <el-button @click="innerVisible = false">取 消</el-button>
              <el-button type="primary" @click="addAdmin">验证</el-button>
            </span>
        </el-dialog>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="valideForm">创建新管理员</el-button>
      </span>
    </el-dialog>

    </el-container>
</template>

<script>

export default {
    name:'adminUser',
    data(){
        return{
            admin:[],
            currentPage: 1,
            pageSize:10,
            total:0,
            formData:{
              name: '',
              phone: '',
              status: '',
              dateTime : []
            },
            selectionRowIds:[],
            centerDialogVisible: false,
            innerVisible:false,
            form:{
              name:'',
              region:''
            },
            createPhone:'',
            createName:'',
            validPassword:'',
            roleValue:[],
            selectedRoleId:''
        }
    },
    mounted(){
      this.initAuthority();
    },
    methods:{
        handleRoleSelection() {
            console.log('Selected Role ID:', this.selectedRoleId);
            // 可以在这里触发其他逻辑，比如根据选中的角色ID获取相关数据等
        },
        initAuthority(){
          this.$request.get("/role/authority",{
            params:{
              id: JSON.parse(localStorage.getItem("admin")).id,
              index: 1
            }
          })
          .then(res =>{
            this.Authority = res.data
            if(res.data == '1'){
              this.getUserList();
              this.initRole();
            }else{
              this.$message.error("你没有权限访问此功能")
            }
          })
          .catch(err =>{
            console.log(err)
          })

        },
        exportproperty(){
            window.open("http://192.168.1.7:8099/file/adminExprot")
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pageSize = val
            this.getUserList();
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.currentPage = val
            this.getUserList();
        },
        // 获取管理员列表
        getUserList(){
          let startTime;
          let endTime;
          if(this.formData.dateTime == null){
            startTime = ''
            endTime = ''
          }else{
            startTime = this.formData.dateTime[0];
            endTime = this.formData.dateTime[1];
          }
          
          this.$request.get("/admin/page",{
            params:{
              page: this.currentPage,
              size: this.pageSize,
              name: this.formData.name,
              phone: this.formData.phone,
              status: this.formData.status,
              startTime: startTime,
              endTime: endTime
            }
          }).then(res=>{
            this.admin = res.data.records;
            this.total = res.data.total;
          })
          .catch(err =>{
            console.error('Error fetching user list:', err);
          })
        },
        //批量修改状态
        changeStatus(){

        },
        //修改状态
        handleSwitchChange(row) {
          // 在这里处理状态切换事件，你可以访问到状态切换的行数据 (row)
          console.log("Switch 状态改变了，行数据为：", row);
          // 这里可以放置你的其他逻辑
          console.log(row.id)
          this.$request.put("/admin/edit",row)
          .then(res=>{
            // let id = res.data.id
            row = res.data
          })
          .catch(err=>{
            console.log(err)
          })
        },
        //删除行数据
        handleDelete(index,row){
          this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if(row.status == true){
              this.$message({
                showClose: true,
                message: '管理员未被禁用，删除失败',
                type: 'warning'
              })
            }else{
              this.selectionRowIds.push(row.id)
              this.$request.delete("/admin/delete",{
                data: this.selectionRowIds
              })
              .then(res => {
                this.$notify({
                  title: '成功',
                  message: "数据已删除",
                  type: 'success'
                })
                this.getUserList()
              })
              .catch(err => {
                console.log(err)
              })
            }
            this.selectionRowIds = []
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });          
          });

          
        },
        initRole(){
          this.$request.get("/role/getRole")
          .then(res => {
            this.roleValue = res.data
            console.log('res:',this.roleValue)
          })
          .catch(err => {

          })
        },
        search(){
          this.getUserList();
        },
        //更新选中的数据集合
        handleSelectionChange(selection){
          // console.log("选中的数据为：",selection)
          this.selectionRowIds = []
          for(let i = 0;i < selection.length;i++){
            this.selectionRowIds.push(selection[i])
          }

          console.log("数组中的数据为",this.selectionRowIds)
        },
        //删除选中的数据
        deleteIds(){
          console.log(this.selectionRowIds.length)
          if(this.selectionRowIds.length == 0){
            this.$message({
              showClose: true,
              message: '请先选择数据',
              type: 'warning'
            })
          }else{
            for(let i = 0;i<this.selectionRowIds.length;i++){
              if(this.selectionRowIds[i].status == true){
                this.$message({
                  showClose: true,
                  message: '启用用户不能被删除',
                  type: 'warning'
                })
                return
              }
            }
            this.$confirm('此操作将永久数据, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              let ids = [];
              this.selectionRowIds.forEach(e =>{
                    ids.push(e.id)
                  })
              this.$request.delete("/admin/delete",{
                      data: ids
              })
              .then(res => {
                this.$notify({
                  title: '成功',
                  message: res.data+"条数据成功删除",
                  type: 'success'
                })
                this.getUserList();
              })
              .catch(err => {
                      console.log(err)
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });          
            })
            
           
          }
        },
        addAdmin(){
          const currentId = JSON.parse(localStorage.getItem('admin')).id
          if(this.validPassword == ""){
            this.$message({
              showClose: true,
              message: '数据未输入',
              type: 'warning'
            })
          }else{
            this.$request.put("/admin/create",{
              roleId:this.selectedRoleId.toString(),
              name:this.createName,
              phone:this.createPhone,
              password:this.validPassword,
              id:currentId,
            })
            .then(res => {
              console.log(res)
              this.$message({
                type:res.data == null?"error":"success",
                message:res.data == null?res.msg:"插入成功",
                showClose:true
              })
              this.initAuthority()
            })
            .catch(err => {
              console.log(err)
            })
            this.innerVisible = false
            this.centerDialogVisible = false
            this.createName = ""
            this.createPhone = ""
            this.validPassword = ""
            this.getUserList()
            console.log(currentId);
          }
        },
        valideForm(){
          if(this.createName=="" || this.createPhone==""){
            this.$message({
              showClose: true,
              message: '数据未输入',
              type: 'warning'
            })
          }else{
            this.innerVisible = true
          }
        },
        reset(){
          this.formData.dateTime = []
          this.formData.name = ''
          this.formData.phone = ''
          this.formData.status = ''
          this.getUserList()
        }
    }
}
</script>

<style>
  .el-row {
    margin-bottom: 20px;

  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>